package com.pug.zixun.service.adminuser;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pug.zixun.bo.AdminUserBo;
import com.pug.zixun.commons.enums.AdminUserResultEnum;
import com.pug.zixun.commons.enums.ResultStatusEnum;
import com.pug.zixun.commons.ex.PugBusinessException;
import com.pug.zixun.commons.ex.PugValidatorException;
import com.pug.zixun.commons.utils.fn.asserts.Vsserts;
import com.pug.zixun.commons.utils.pwd.MD5Util;
import com.pug.zixun.mapper.AdminUserMapper;
import com.pug.zixun.pojo.AdminRole;
import com.pug.zixun.pojo.AdminUser;
import com.pug.zixun.vo.AdminUserRegVo;
import com.pug.zixun.vo.AdminUserVo;
import com.pug.zixun.vo.LoginVo;
import com.pug.zixun.vo.StatusUpdateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * AdminUserServiceImpl实现类
 * 创建人:yykk<br/>
 * 时间：2022-07-15 20:48:26 <br/>
 * 源码下载：前台代码 git clone https://gitee.com/kekesam/kuangstudy-pug-ui.git
 * 飞哥B站地址：后台代码 git clone https://gitee.com/kekesam/kuangstudy-pug-parent.git
 *
 * @version 1.0.0<br />
 */
@Service
@Slf4j
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements IAdminUserService {

    /**
     * 保存用户角色信息
     *
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public int saveUserRole(Long userId,  Long roleId){
        int count = this.baseMapper.countUserRole(userId, roleId);
        if (count==0){
            return this.baseMapper.saveUserRole(userId,roleId);
        }
        return 0;
    }

    /**
     * 删除用户角色信息
     *
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public int delUserRole(Long userId,  Long roleId){
        int count = this.baseMapper.countUserRole(userId, roleId);
        if (count > 0){
            return this.baseMapper.delUserRole(userId,roleId);
        }
        return 0;
    }
    /**
     * 查询分页&搜索后台用户管理
     *
     * @param adminuserVo
     * @return IPage<AdminUser>
     * 创建人:yykk
     * 创建时间：2022-07-15 20:48:26
     * @version 1.0.0
     */
    @Override
    public IPage<AdminUserBo> findAdminUserPage(AdminUserVo adminuserVo) {
        // 设置分页信息
        Page<AdminUser> page = new Page<>(adminuserVo.getPageNo(), adminuserVo.getPageSize());
        // 设置查询条件
        LambdaQueryWrapper<AdminUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // lambdaQueryWrapper.select(AdminUser.class, column -> !column.getColumn().equals("description"));
        // 根据关键词搜索信息
        //查询发布的 0 未发布  1 发布
        lambdaQueryWrapper.eq(adminuserVo.getStatus() != null, AdminUser::getStatus, adminuserVo.getStatus());
        // 多列搜索
        lambdaQueryWrapper.and(Vsserts.isNotEmpty(adminuserVo.getKeyword()), wrapper -> wrapper
                .like(AdminUser::getUsername, adminuserVo.getKeyword())
                .or()
                .like(AdminUser::getAccount, adminuserVo.getKeyword())
        );
        // 根据时间排降序
        lambdaQueryWrapper.orderByDesc(AdminUser::getCreateTime);
        // 查询分页返回
        IPage<AdminUser> results = this.page(page, lambdaQueryWrapper);
        return tranferPageBo(results, AdminUserBo.class);
    }

    /**
     * 查询后台用户管理列表信息
     *
     * @return
     * @method: findAdminUserList
     * @result : List<AdminUser>
     * 创建人:yykk
     * 创建时间：2022-07-15 20:48:26
     * @version 1.0.0
     */
    @Override
    public List<AdminUserBo> findAdminUserList() {
        // 1：设置查询条件
        LambdaQueryWrapper<AdminUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 2：查询发布的 0 未发布  1 发布
        lambdaQueryWrapper.eq(AdminUser::getStatus, 1);
        lambdaQueryWrapper.eq(AdminUser::getIsdelete, 0);
        // 3: 查询返回
        return tranferListBo(this.list(lambdaQueryWrapper), AdminUserBo.class);
    }

    /**
     * 根据id查询后台用户管理明细信息
     *
     * @param id
     * @return AdminUser
     * 创建人:yykk
     * 创建时间：2022-07-15 20:48:26
     * @version 1.0.0
     */
    @Override
    public AdminUserBo getAdminUserById(Long id) {
        return tranferBo(this.getById(id), AdminUserBo.class);
    }


    /**
     * 保存&修改后台用户管理
     *
     * @return AdminUser
     * 创建人:yykk
     * 创建时间：2022-07-15 20:48:26
     * @version 1.0.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminUserBo saveupdateAdminUser(AdminUserRegVo adminUserRegVo) {
        // 1：查询账号是否已经存在
        AdminUser editUser = this.getById(adminUserRegVo.getId());
        if ((adminUserRegVo != null && adminUserRegVo.getId() == null) ||
                (editUser != null && !editUser.getAccount().equals(adminUserRegVo.getAccount()))) {// 只有保存的时候才去做
            LambdaQueryWrapper<AdminUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AdminUser::getAccount, adminUserRegVo.getAccount());
            int count = this.count(lambdaQueryWrapper);
            // 根据账号查询是否注册，如果注册count>0
            if (count > 0) {
                throw new PugBusinessException(AdminUserResultEnum.ACCOUNT_REG_ERROR);
            }
        }

        // 保存数据转换成DO
        AdminUser adminUser = tranferBo(adminUserRegVo, AdminUser.class);
        // 密码加密
        if (Vsserts.isNotEmpty(adminUserRegVo.getPassword())) {
            adminUser.setPassword(MD5Util.md5slat(adminUser.getPassword()));
        } else {
            // 把原始密码放回去
            if (editUser != null && Vsserts.isNotEmpty(editUser.getPassword())) {
                adminUser.setPassword(editUser.getPassword());
            }
        }


        // 入库，mybatis-plus在执行save/saveOrUpdate自动会返回保存数据以后的id的值
        boolean flag = this.saveOrUpdate(adminUser);
        // 如果保存用户成功
        if (flag) {
            //开始给保存的用户绑定角色
            int count = this.baseMapper.countUserRole(adminUser.getId(), adminUserRegVo.getRoleId());
            if (count == 0) {
                this.baseMapper.saveUserRole(adminUser.getId(), adminUserRegVo.getRoleId());
            }
        }
        // 返回
        return flag ? tranferBo(adminUser, AdminUserBo.class) : null;
    }

    /**
     * 根据id删除后台用户管理
     *
     * @param id
     * @return int
     * 创建人:yykk
     * 创建时间：2022-07-15 20:48:26
     * @version 1.0.0
     */
    @Override
    public int deleteAdminUserById(Long id) {
        AdminUser user = this.getById(id);
        if(user!=null) {
            AdminUser newUser = new AdminUser();
            newUser.setId(id);
            newUser.setIsdelete(1);
            boolean b = this.updateById(newUser);
            return 1;
        }
        return 0;
    }

    /**
     * 根据id删除
     *
     * @param ids
     * @return boolean
     * 创建人:yykk
     * 创建时间：2022-07-15 20:48:26
     * @version 1.0.0
     */
    @Override
    public boolean delBatchAdminUser(String ids) {
        try {
            // 1 : 把数据分割
            String[] strings = ids.split(",");
            // 2: 组装成一个List<AdminUser>
            List<AdminUser> adminuserList = Arrays.stream(strings).map(idstr -> {
                AdminUser adminuser = new AdminUser();
                // 逻辑删除
                adminuser.setIsdelete(1);
                adminuser.setId(new Long(idstr));
                return adminuser;
            }).collect(Collectors.toList());
            // 3: 批量删除
            return this.updateBatchById(adminuserList);
        } catch (Exception ex) {
            throw new PugValidatorException(ResultStatusEnum.SERVER_DB_ERROR);
        }
    }


    /**
     * 登录
     *
     * @param loginVo
     * @return
     */
    @Override
    public AdminUser login(LoginVo loginVo) {
        LambdaQueryWrapper<AdminUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminUser::getAccount, loginVo.getUsername());
        AdminUser user = this.getOne(lambdaQueryWrapper);
        return user;
    }

    /**
     * 状态更新
     *
     * @param adminUserRegVo
     * @return
     */
    @Override
    public boolean updateAdminUser(StatusUpdateVo adminUserRegVo) {
        // 保存数据转换成DO
        AdminUser adminUser = tranferBo(adminUserRegVo, AdminUser.class);
        return updateById(adminUser);
    }


    @Override
    public List<String> getRoleNames(Long userId) {
        List<AdminRole> byUserRoles = this.baseMapper.findByUserRoles(userId);
        if (!CollectionUtils.isEmpty(byUserRoles)) {
            return byUserRoles.stream().map(role -> role.getRoleName()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 根据用户id查询角色信息
     * @param userId
     * @return
     */
    @Override
    public List<Long> findByUserRoleIds(Long userId){
        List<AdminRole> byUserRoles = this.baseMapper.findByUserRoles(userId);
        if (!CollectionUtils.isEmpty(byUserRoles)) {
            return byUserRoles.stream().map(role -> role.getId()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<String> findByUserPermission(Long userId) {
        return this.baseMapper.findByUserPermission(userId);
    }

}